#!/bin/bash
# shellcheck disable=SC2001

# Device specific configs
DEVICENAME=$(cat /sys/devices/virtual/dmi/id/product_name)
VENDOR=$(cat /sys/devices/virtual/dmi/id/sys_vendor)
SCREEN_WIDTH=$(cat /sys/class/graphics/fb0/virtual_size 2>/dev/null | cut -d ',' -f 1 || echo "0")
SCREEN_HEIGHT=$(cat /sys/class/graphics/fb0/virtual_size 2>/dev/null | cut -d ',' -f 2 || echo "0")

source /usr/bin/sk-utils.sh

log_info() {
    echo -e "${GRAY}[$(get_timestamp)]${NC} ${BLUE}INFO: $1${NC}" >&2
}

log_success() {
    echo -e "${GRAY}[$(get_timestamp)]${NC} ${GREEN}SUCCESS: $1${NC}" >&2
}

log_warning() {
    echo -e "${GRAY}[$(get_timestamp)]${NC} ${YELLOW}WARNING: $1${NC}" >&2
}

log_error() {
    echo -e "${GRAY}[$(get_timestamp)]${NC} ${RED}ERROR: $1${NC}" >&2
}

# Detect the currently active/connected screen and get its EDID
# Priority: eDP > LVDS > DSI > other connected displays
get_screen_edid_path() {
    (
        # Enable nullglob in subshell: unmatched globs expand to nothing
        shopt -s nullglob 2>/dev/null || setopt nullglob 2>/dev/null

        local priority_connectors=("eDP" "LVDS" "DSI")
        local drm_connector=""
        local edid_path=""

        # First, try to find internal display (eDP, LVDS, DSI)
        for connector_type in "${priority_connectors[@]}"; do
            for drm_path in /sys/class/drm/card*-"${connector_type}"-*/status; do
                if [[ -f "$drm_path" ]] && [[ "$(cat "$drm_path")" == "connected" ]]; then
                    edid_path="${drm_path%/status}/edid"
                    drm_connector=$(sed 's|.*/card[^-]*-\(.*\)/status|\1|' <<<"$drm_path")
                    log_info "drm_path: $drm_path, edid_path: $edid_path, drm_connector: $drm_connector"
                    if [[ -f "$edid_path" ]]; then
                        echo "$edid_path"
                        echo "$drm_connector"
                        return 0
                    fi
                fi
            done
        done

        # If no internal display found, use any connected display
        for drm_path in /sys/class/drm/card*/status; do
            if [[ -f "$drm_path" ]] && [[ "$(cat "$drm_path")" == "connected" ]]; then
                edid_path="${drm_path%/status}/edid"
                drm_connector=$(sed 's|.*/card[^-]*-\(.*\)/status|\1|' <<<"$drm_path")
                # log_info "drm_path: $drm_path, edid_path: $edid_path"
                if [[ -f "$edid_path" ]]; then
                    echo "$edid_path"
                    echo "$drm_connector"
                    return 0
                fi
            fi
        done

        return 1
    )
}

# Default right rotation
DEFAULT_X11_ROTATION="right"
DEFAULT_DRM_CONNECTOR="eDP-1"
DEFAULT_DRM_ROTATION="panel_orientation=right_side_up"
DEFAULT_ROTATE_OFFSET="1"

X11_ROTATION=""
DRM_CONNECTOR=""
DRM_ROTATION=""
ROTATE_OFFSET=""

{
    read -r EDID_PATH
    read -r DRM_CONNECTOR
} < <(get_screen_edid_path)
log_info "EDID_PATH: $EDID_PATH"
log_info "DRM_CONNECTOR: $DRM_CONNECTOR"

if [[ -n "$EDID_PATH" ]]; then
    SCREEN_MODEL_NAME=$(cat "$EDID_PATH" | parse-edid 2>/dev/null | grep "ModelName" | cut -d \" -f 2 | sed 's/[^a-zA-Z0-9_-]//g')
else
    SCREEN_MODEL_NAME=""
fi

AYA_RIGHT_LIST=(
    "AYA NEO FOUNDER"
    "AYA NEO 2021"
    "AYANEO 2021"
    "NEXT"
    "AYANEO 2"
    "GEEK"
)

AYA_LEFT_LIST=(
    "AIR"
    "SLIDE"
    "FLIP"
)

LGO_LEFT_LIST=(
    "83E1"
)

GPD_RIGHT_LIST=(
    "G1617-01"
    "G1621-02"
    "G1619-01"
    "MicroPC"
)

AOKZOE_LEFT_LIST=(
    "AOKZOE A1"
    "AOKZOE A2"
)

ONEXPLAYER_LEFT_LIST=(
    "ONE XPLAYER"
    "ONEXPLAYER 1"
    "ONEXPLAYER GUNDAM"
    "ONEXPLAYER Mini"
    "ONEXPLAYER mini"
    "ONEXPLAYER F1"
    "ONEXPLAYER 2"
    "ONEXPLAYER X1"
)

AYN_LEFT_LIST=(
    "Loki Max"
    "Loki MiniPro"
    "Loki Zero"
)

ORANGEPI_RIGHT_LIST=(
    "NEO-01"
    "G1621-02"
)

# LEFT_LIST="${OXP_LIST}:${AIR_LIST}:${AOK_LIST}:${AYN_LIST}:${LENOVO_LIST}"
# RIGHT_LIST="${AYA_LIST}:${GPD_LIST}"

LEFT_LIST=(
    "${AYA_LEFT_LIST[@]}"
    "${LGO_LEFT_LIST[@]}"
    "${AOKZOE_LEFT_LIST[@]}"
    "${ONEXPLAYER_LEFT_LIST[@]}"
    "${AYN_LEFT_LIST[@]}"
)

RIGHT_LIST=(
    "${AYA_RIGHT_LIST[@]}"
    "${GPD_RIGHT_LIST[@]}"
    "${ORANGEPI_RIGHT_LIST[@]}"
)

NORMAL_MODEL_LIST=(
    "TL070FVXS01"
    "TL070FVXS02"
    "TL070FDXS01"
    "PN8007QB1"
    "NS080WUM"
)

for product in "${LEFT_LIST[@]}"; do
    if [[ "$DEVICENAME" =~ "$product" ]]; then
        ROTATE_OFFSET="3"
        X11_ROTATION="left"
        DRM_ROTATION="panel_orientation=left_side_up"
        break
    fi
done

for product in "${RIGHT_LIST[@]}"; do
    if [[ "$DEVICENAME" =~ "$product" ]]; then
        ROTATE_OFFSET="1"
        X11_ROTATION="right"
        DRM_ROTATION="panel_orientation=right_side_up"
        break
    fi
done

# 如果未设置，则使用默认值
if [[ -z "$DRM_CONNECTOR" ]]; then
    DRM_CONNECTOR="$DEFAULT_DRM_CONNECTOR"
fi
if [[ -z "$DRM_ROTATION" ]]; then
    DRM_ROTATION="$DEFAULT_DRM_ROTATION"
fi
if [[ -z "$ROTATE_OFFSET" ]]; then
    ROTATE_OFFSET="$DEFAULT_ROTATE_OFFSET"
fi
if [[ -z "$X11_ROTATION" ]]; then
    X11_ROTATION="$DEFAULT_X11_ROTATION"
fi

# 是否不进行旋转
FORCE_NOT_ROTATE=false

# 不进行旋转的屏幕
for model in "${NORMAL_MODEL_LIST[@]}"; do
    if [[ "$SCREEN_MODEL_NAME" =~ "$model" ]]; then
        FORCE_NOT_ROTATE=true
        break
    fi
done

if [[ "$FORCE_NOT_ROTATE" == true || "$SCREEN_WIDTH" -ge "$SCREEN_HEIGHT" ]]; then
    ROTATE_OFFSET="0"
    X11_ROTATION="normal"
    unset DRM_CONNECTOR
    unset DRM_ROTATION
fi

if [[ -n "$DRM_CONNECTOR" && -n "$DRM_ROTATION" ]]; then
    VIDEO_PARA="$DRM_CONNECTOR:$DRM_ROTATION"
else
    unset VIDEO_PARA
fi

log_info "Sceeen size: $SCREEN_WIDTH x $SCREEN_HEIGHT"
log_info "SCREEN_MODEL_NAME: $SCREEN_MODEL_NAME"
log_info "ROTATE_OFFSET: $ROTATE_OFFSET"
log_info "X11_ROTATION: $X11_ROTATION"
log_info "VIDEO_PARA: $VIDEO_PARA"

export FBCON_PARA="rotate:$ROTATE_OFFSET"
export ROTATE_OFFSET="$ROTATE_OFFSET"
export X11_ROTATION="$X11_ROTATION"
export VIDEO_PARA="$VIDEO_PARA"
